package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import model.User;
import net.sf.json.JSONObject;
import utils.RequestUtil;
import utils.JdbcUtil;
import utils.ResponseUtil;
import dao.UserDao;
import dao.UserEventDao;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet(urlPatterns = { "/UserServlet" })
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	JdbcUtil dbUtil = new JdbcUtil();
	UserDao uDao = new UserDao();
	UserEventDao ueDao = new UserEventDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = RequestUtil.get(request.getParameter("method"));

		if (method.equals("addUser")) {
			addUser(request, response);
		}
		if (method.equals("getUserInfoList")) {
			getUserInfoList(request, response);
		}
		if (method.equals("deleteUser")) {
			deleteUser(request, response);
		}
		if (method.equals("search")) {
			searchUser(request, response);
		}
		if (method.equals("showUserInfo")) {
			showUserInfo(request, response);
		}

	}

	private void showUserInfo(HttpServletRequest request, HttpServletResponse response) {
		String id = RequestUtil.get(request.getParameter("uId"));
		if (id.trim() == "")
			return;
		int uId = Integer.parseInt(id);
		User user = uDao.getUserByUid(uId);
		request.setAttribute("user", user);
		request.setAttribute("done", "userManage.jsp");
		try {
			request.getRequestDispatcher("userManage.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void addUser(HttpServletRequest request, HttpServletResponse response) {
		String username = RequestUtil.get(request.getParameter("username"));
		//String password = RequestUtil.get(request.getParameter("password"));
		String phonenumber = RequestUtil.get(request.getParameter("phonenumber"));
		String email = RequestUtil.get(request.getParameter("email"));
		JSONObject result = new JSONObject();
		User u = new User();
		u.setUserName(username);
		//u.setPassword(password);
		u.setPhoneNumber(phonenumber);
		u.setEmail(email);
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();
		Set<ConstraintViolation<User>> violations = validator.validate(u);
		if (violations.size() == 0) {
			// 验证无错
			User user = uDao.getUser(phonenumber);
			if (user != null) {// 已经有这个电话对应的用户
				result.put("exist", "-1");// -1，已经存在没有插入
			} else {
				if (uDao.addUser(u) == 1) {// 添加成功
					result.put("exist", "1");
				} else {
					result.put("exist", "0");
				}
			}
		} else {
			result.put("check", "0");
		}
		try {
			ResponseUtil.write(result, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void searchUser(HttpServletRequest request, HttpServletResponse response) {
		String info = RequestUtil.get(request.getParameter("info"));
		List<User> infoList = uDao.getserchUserInfo(info);// 从数据库获取数据
		request.setAttribute("infoList", infoList);
		request.setAttribute("done", "userManage.jsp");
		try {
			request.getRequestDispatcher("userManage.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}

	}

	private void getUserInfoList(HttpServletRequest request, HttpServletResponse response) {
		List<User> infoList = uDao.getUserInfo();// 从数据库获取数据
		// String json = JSONArray.fromObject(infoList).toString();
		// response.getWriter().write(json);
		request.setAttribute("infoList", infoList);
		request.setAttribute("done", "userManage.jsp");
		try {
			request.getRequestDispatcher("userManage.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

	private void deleteUser(HttpServletRequest request, HttpServletResponse response) {
		String uId = RequestUtil.get(request.getParameter("uId"));
		// JSONObject result = new JSONObject();

		if (ueDao.getUserEvent(uId) == 1) {// 该用户已有注册信息
			request.setAttribute("exist", "metaDBManage.jsp");// -1，不能删除
		} else {
			if (uDao.deletUser(uId) == 1) {// 删除成功
				request.setAttribute("succeed", "metaDBManage.jsp");
			} else {
				request.setAttribute("fail", "metaDBManage.jsp");
			}
		}
		// ResponseUtil.write(result, response);
		getUserInfoList(request, response);
	}
}
